import request from "./request";
import { ElMessage } from "element-plus";
import cache from "@/utils/cache";

const CACHE_KEY = {
  MENU_LIST: "menu_list",
  MENU_TOP_LIST: "menu_top_list",
  MENU_DETAIL: "menu_detail_",
  MENU_CHILDREN: "menu_children_",
};

const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

/**
 * 统一的错误处理
 * @param {Error} error - 错误对象
 * @param {string} customMessage - 自定义错误消息
 */
const handleError = (error, customMessage = "操作失败") => {
  console.error(error);
  ElMessage.error(customMessage);
  throw error;
};

/**
 * 获取所有菜单
 * @returns {Promise} - 返回菜单列表数据
 */
export async function getMenus() {
  try {
    const cacheKey = CACHE_KEY.MENU_LIST;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: "/Menu/list",
      method: "get",
    });

    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取菜单列表失败");
  }
}

/**
 * 获取顶级菜单
 * @returns {Promise} - 返回菜单列表数据
 */
export async function getTopMenus() {
  try {
    const cacheTopKey = CACHE_KEY.MENU_TOP_LIST;
    const cachedData = cache.get(cacheTopKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: "/Menu/topList",
      method: "get",
    });

    cache.set(cacheTopKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取菜单列表失败");
  }
}

/**
 * 获取菜单详情
 * @param {number} id - 菜单ID
 * @returns {Promise} - 返回菜单详情
 */
export async function getMenu(id) {
  try {
    if (!id) throw new Error("菜单ID不能为空");

    const cacheKey = `${CACHE_KEY.MENU_DETAIL}${id}`;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: `/Menu/detail/${id}`,
      method: "get",
    });

    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取菜单详情失败");
  }
}

/**
 * 创建新菜单
 * @param {Object} menuData - 菜单数据
 * @returns {Promise} - 返回创建结果
 */
export const createMenu = async (menuData) => {
  try {
    if (!menuData.menuName) throw new Error("菜单名称不能为空");

    const response = await request({
      url: "/Menu/create",
      method: "POST",
      data: menuData,
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.MENU_LIST);
    if (menuData.menuParentId) {
      cache.remove(`${CACHE_KEY.MENU_CHILDREN}${menuData.menuParentId}`);
    }

    return response;
  } catch (error) {
    handleError(error, "创建菜单失败");
  }
};

/**
 * 更新菜单信息
 * @param {Object} menuData - 包含ID的菜单数据
 * @returns {Promise} - 返回更新结果
 */
export const updateMenu = async (menuData) => {
  try {
    if (!menuData.menuId) throw new Error("菜单ID不能为空");
    if (!menuData.menuName) throw new Error("菜单名称不能为空");

    const response = await request({
      url: `/Menu/update/${menuData.menuId}`,
      method: "PUT",
      data: menuData,
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.MENU_LIST);
    cache.remove(`${CACHE_KEY.MENU_DETAIL}${menuData.menuId}`);
    if (menuData.menuParentId) {
      cache.remove(`${CACHE_KEY.MENU_CHILDREN}${menuData.menuParentId}`);
    }

    return response;
  } catch (error) {
    handleError(error, "更新菜单失败");
  }
};

/**
 * 删除菜单
 * @param {number} id - 要删除的菜单ID
 * @returns {Promise} - 返回删除结果
 */
export const deleteMenu = async (id) => {
  try {
    if (!id) throw new Error("菜单ID不能为空");

    const response = await request({
      url: `/Menu/${id}`,
      method: "DELETE",
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.MENU_LIST);
    cache.remove(`${CACHE_KEY.MENU_DETAIL}${id}`);
    cache.removeByPrefix(CACHE_KEY.MENU_CHILDREN);

    return response;
  } catch (error) {
    handleError(error, "删除菜单失败");
  }
};

/**
 * 获取子菜单列表
 * @param {number} parentId - 父菜单ID
 * @returns {Promise} - 返回子菜单列表
 */
export const getMenuChildren = async (parentId) => {
  try {
    if (!parentId) throw new Error("父菜单ID不能为空");

    const cacheKey = `${CACHE_KEY.MENU_CHILDREN}${parentId}`;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: `/Menu/children/${parentId}`,
      method: "get",
    });

    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取子菜单失败");
  }
};
